package com.guodi.map.controller;

import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.minio.util.MinioUtil;
import com.guodi.core.tool.api.R;
import com.guodi.map.entity.MapParamScheme;
import com.guodi.map.entity.MapProject;
import com.guodi.map.entity.MapProjectFile;
import com.guodi.map.service.*;
import com.guodi.map.utils.VerificationUtil;
import com.guodi.map.vo.ApiMapProject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.*;


/**
 * @描述：地图图层专题表控制类
 * @作者: 代鹏刚
 * @日期: 2019-12-11
 */
@Validated
@RestController
@RequestMapping("/MapProject")
@Api(value = "API - MapProjectController", tags = "地图图层专题表")
public class MapProjectController extends BaseController {

    @Autowired
    private IMapProjectService mapProjectService;
    @Autowired
    private IMapParamSchemeService mapParamSchemeService;
    @Autowired
    private IMapProjectDirService mapProjectDirService;
    @Autowired
    private IMapProjectAuthService mapProjectAuthService;
    @Autowired
    private IMapProjectFileService mapProjectFileService;
    @Autowired
    private IMapCommonService commonService;

    /**
    * @描述: 根据实体属性分页查询
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2019-12-11
    **/
    @PostMapping("/listByEntity")
    @ApiOperation(value = " 根据实体属性分页查询")
    @ApiImplicitParams(@ApiImplicitParam(name = "name", value = "专题名称", required = false, dataType = "string", paramType = "query"))
    public R listByEntity(@ApiIgnore MapProject mapProject){
        List<MapProject> list = mapProjectService.listByEntity(mapProject);
        return R.data(list);
    }

    /**
     * @描述: 根据主键查询
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-11
     **/
    @PostMapping("/findById")
    @ApiOperation(value = "根据主键查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    public R findById(String id) {
        if(StringUtils.isBlank(id)){
            return R.fail(StatusCode.ERROR_CODE_40005,"id不能为空");
        }
        MapProject mapProject = mapProjectService.getById(id);
        return R.data(mapProject);
    }

    /**
    * @描述: 根据code查询
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/3/11 10:01
    **/
    @PostMapping("/findByCode")
    @ApiOperation(value = "根据code查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "专题编码", required = true, dataType = "string", paramType = "query")
    })
    public R findByCode(String code) {
        List<MapProject> mapProject = (List<MapProject>)mapProjectService.listByMap(VerificationUtil.verifyMapByCode(code,null));
        return R.data(mapProject);
    }

    /**
     * @描述: 新增
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-11
     **/
    @PostMapping("/save")
    @ApiOperation(value = "新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resourceId", value = "资源目录ID", required = true, dataType = "string", paramType = "query")
    })
    public R save(@Valid ApiMapProject apiMapProject){
        MapProject mapProject = new MapProject();
        BeanUtils.copyProperties(apiMapProject,mapProject);
        if (!prepareData(mapProject, true)) {
            return R.fail(StatusCode.ERROR_CODE_40005,"该专题名称已存在，请更改！");
        }
        List<MapProject> mapProjectList = (List<MapProject>)mapProjectService.listByMap(VerificationUtil.verifyMapByCode(mapProject.getCode(),null));
        if(mapProjectList.size() > 0){
            return R.fail(StatusCode.ERROR_CODE_40005,"该专题编码已存在，请更改！");
        }
        String id = UuidUtil.get32UUID();
        mapProject.setId(id);
        Integer sort = commonService.getMaxSort(null,"map_project");
        mapProject.setSort(sort + 1);
        mapProjectService.save(mapProject);
        return R.data(mapProject);
    }

    /**
     * @描述: 修改
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-11
     **/
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public R update(MapProject mapProject) {
        if(!prepareData(mapProject, false)){
            return R.fail(StatusCode.ERROR_CODE_40005,"该专题名称已存在，请更改！");
        }
        List<MapProject> mapProjectList = (List<MapProject>)mapProjectService.listByMap(VerificationUtil.verifyMapByCode(mapProject.getCode(),null));
        if(mapProjectList.size() > 1 || (mapProjectList.size() == 1 && !mapProjectList.get(0).getId().equals(mapProject.getId()))){
            return R.fail(StatusCode.ERROR_CODE_40005,"该专题编码已存在，请更改！");
        }
        mapProjectService.updateById(mapProject);
        return R.data(mapProject);
    }

    /**
     * @描述: 根据主键删除
     * @入参: id
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-11
     **/
    @PostMapping("/delete")
    @ApiOperation(value = "根据主键删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    @Transactional(rollbackFor = Exception.class)
    public R delete(String id){
        //获取专题目录附件信息
        Map map = new HashMap();
        map.put("project_id",id);
        //删除表数据
        mapProjectService.removeById(id);
        //删除专题目录表数据
        mapProjectDirService.deleteByProjectId(id);
        //删除专题授权数据
        mapProjectAuthService.removeByMap(map);
        //删除FDFS附件
        List<MapProjectFile> mapProjectFiles = mapProjectFileService.listByMap(map);
        for (MapProjectFile mapProjectFile : mapProjectFiles) {
            if(mapProjectFile.getType().equals("2") && StringUtils.isNotBlank(mapProjectFile.getFilePath())){
                MinioUtil.removeFile(mapProjectFile.getFilePath());
            }
        }
        //删除专题附件表
        mapProjectFileService.removeByMap(map);
        return R.data(null);
    }

    /**
    * @描述: 获取地图参数下拉框
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2019/12/13 10:13
    **/
    @PostMapping("/getMapParam")
    @ApiOperation(value = "获取地图参数下拉框")
    public R getMapParam(){
        List<MapParamScheme> mapParamSchemes = mapParamSchemeService.list();
        List<Map> mapList = new ArrayList<>();
        if(mapParamSchemes != null && mapParamSchemes.size() > 0){
            for (MapParamScheme mapParamList:mapParamSchemes
                 ) {
                Map map = new HashMap();
                map.put("label",mapParamList.getName());
                map.put("value",mapParamList.getId());
                mapList.add(map);
            }
        }
        return R.data(mapList);
    }

    private boolean prepareData(MapProject mapProject, boolean isSave) {
        List<MapProject> list = (List<MapProject>)mapProjectService.listByMap(VerificationUtil.verifyMap(mapProject.getName(),null));
        if(isSave){
            //新增时，验证是否重名
            if(list.size() > 0){
                return false;
            }
            mapProject.setCreator(getUser().getUserId().toString());
            mapProject.setCreateTime(new Date());
            //防止误修改
            mapProject.setModifier(null);
            mapProject.setModifyTime(null);
            return true;
        }else{
            //修改时，验证是否重名
            if(list.size() > 0 && !list.get(0).getId().equals(mapProject.getId())){
                return false;
            }
            mapProject.setModifier(getUser().getUserId().toString());
            mapProject.setModifyTime(new Date());
            //防止误修改
            mapProject.setCreator(null);
            mapProject.setCreateTime(null);
            return true;
        }
    }
}
